/*
 * Created on Aug 26, 2005
 *
 */
package org.mushroomdb.parser;

import java.lang.reflect.InvocationTargetException;

import org.apache.log4j.Logger;
import org.mushroomdb.parser.composite.CompositeParser;
import org.mushroomdb.util.Properties;
import org.mushroomdb.util.PropertiesHelper;



/**
 * @author mchiodi
 *
 */
public class ParserService {
	private static ParserService instanceReference;
	private Parser parser;
	private Logger logger;

	/**
	 * Constructor default privado.
	 */
	private ParserService() {
		this.logger = Logger.getLogger(this.getClass());
	}
	
	/**
	 * Devuelve la referencia al ParserService.
	 * @return
	 */
	public static ParserService getInstance() {
		if (ParserService.instanceReference == null) {
			ParserService.instanceReference = new ParserService();
		}
		return ParserService.instanceReference;
	}
	
	/**
	 * Devuelve el parser provisto por el servicio.
	 * @return
	 */
	public Parser getParser() {
		if (this.parser == null) {
			this.loadParser();
		}
		return this.parser;
	}
	
	/**
	 * Arma el parser utilizando las configuraciones en el archivo de propiedades.
	 */
	private void loadParser() {
		CompositeParser compositeParser = new CompositeParser();
		
		int index = 1;
		String parserClass = null;
		do {
			parserClass = Properties.getProperty(PropertiesHelper.PARSER + "." + index); //$NON-NLS-1$
			if (parserClass != null) {
				Parser parser = this.getParserInstance(parserClass);
				if (parser != null) {
					compositeParser.addParser(parser);
					logger.info("Parser " + parserClass + " registered."); //$NON-NLS-1$ //$NON-NLS-2$
				} else {
					logger.warn("Parser " + parserClass + " was not registered."); //$NON-NLS-1$ //$NON-NLS-2$
				}
			}
			index++;
		} while (parserClass != null);
		
		this.parser = compositeParser;
		
	}

	/**
	 * Obtiene la instancia de parser a partir del nombre de su clase.
	 * @param className
	 * @return
	 */
	private Parser getParserInstance(String className) {
		try {
			Class clazz = Class.forName(className);
			return (Parser) clazz.getConstructor(new Class[] {}).newInstance(new Object[] {});
		} catch (ClassNotFoundException e) {
			this.logger.error(className,e);
			return null;
		} catch (SecurityException e) {
			this.logger.error(className,e);
			return null;
		} catch (NoSuchMethodException e) {
			this.logger.error(className,e);
			return null;
		} catch (IllegalArgumentException e) {
			this.logger.error(className,e);
			return null;
		} catch (InstantiationException e) {
			this.logger.error(className,e);
			return null;
		} catch (IllegalAccessException e) {
			this.logger.error(className,e);
			return null;
		} catch (InvocationTargetException e) {
			this.logger.error(className,e);
			return null;
		}
	}
}
